<template>
  <div class="common-map">
    <div id="map-container"
      class="map-container"></div>
  </div>
</template>

<script>
  //引入绘图插件
  import 'leaflet-draw';
  import 'leaflet-draw/dist/leaflet.draw.css';
  const wellknown = require('wellknown');

  const mapConfig = {
    // 基础底图
    baseLayerUrl: 'http://t{s}.tianditu.gov.cn/DataServer?T=img_c&X={x}&Y={y}&L={z}&tk=ffa5ef8e4ea43caf693fa0097f8258a6',
    // 基础底图注记
    baseLabelLayer: 'http://t{s}.tianditu.gov.cn/DataServer?T=cia_c&X={x}&Y={y}&L={z}&tk=ffa5ef8e4ea43caf693fa0097f8258a6'
    // // 国界
    // nationalBoundaries: 'http://49.4.8.203:8091/mapserver/vmap/WMTS/1.0/xzqh_gj/xzqh_gj/getTile/{z}/{y}/{x}',
    // // 市县区划
    // shengshixianBoundaries: 'http://49.4.8.203:8091/mapserver/vmap/WMTS/1.0/xzqh/xzqh/getTile/{z}/{y}/{x}',
    // // 注记
    // baseLabelZJLayer: 'http://49.4.8.203:8091/mapserver/label/WMTS/1.0/xzqh_zj/xzqh_zj/getTile/{z}/{y}/{x}'
  };
  const f_shape =
    'SRID=4490;MULTIPOLYGON(((106.502421 29.613777,106.5037758 29.6137687,106.5035168 29.6126349,106.5022284 29.6129341,106.502421 29.613777)))';

  export default {
    name: 'theMap2',
    data() {
      return {
        map: null,
        spotGroup: null,
        drawGroup: null,
        polygonHander: null,
        polylineHander: null
      };
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        //初始化
        this.map = L.map('map-container', {
          crs: L.CRS.EPSG4326, //坐标系
          center: [35.639, 105.55],
          zoom: 4,
          // 隐藏右下角官方图标
          attributionControl: false,
          // 隐藏左上角zoom控制图标(+ - 按钮)
          zoomControl: false
          // doubleClickZoom: false
        });

        //引入图层
        L.tileLayer(mapConfig.baseLayerUrl, {
          subdomains: ['0', '1', '2', '3', '4'],
          zoomOffset: 1,
          // 超过17级进行放大，保证不会出现未找到服务的提示
          maxNativeZoom: 17,
          maxZoom: 20
        }).addTo(this.map);

        //引入注记
        L.tileLayer(mapConfig.baseLabelLayer, {
          subdomains: ['0', '1', '2', '3', '4'],
          zoomOffset: 1
        }).addTo(this.map);

        // 图斑形状
        this.spotGroup = new L.FeatureGroup();
        this.spotGroup.addTo(this.map);

        // 绘制形状的集合
        this.drawGroup = new L.FeatureGroup();
        this.drawGroup.addTo(this.map);
        // 初始化画图
        this.drawPolygon();
        this.drawPolyline();
        this.mapOperate();
      },
      polylineDraw() {
        this.polygonHander.disable();
        this.polylineHander.enable();
      },
      polygonDraw() {
        this.polylineHander.disable();
        this.polygonHander.enable();
      },
      // 绘制多边形
      drawPolygon() {
        L.drawLocal.draw.handlers.polygon = {
          tooltip: {
            start: '点击地图开始绘制多边形',
            cont: '继续选择',
            end: '点击第一个顶点或者双击完成绘制'
          }
        };
        this.polygonHander = new L.Draw.Polygon(this.map, {
          shapeOptions: {
            weight: 1,
            color: '#ff0000',
            opacity: 0.8,
            fillColor: '#ff0000'
          }
        });
      },
      mapOperate() {
        //画图创建事件
        this.map.on(L.Draw.Event.CREATED, (event) => {
          const { layer, layerType } = event;
          // drawGroup,groupLayer,把画图的图层添加到图层组方便管理
          // 需要先把layer加到地图上，才能再加popup
          this.drawGroup.addLayer(layer);
          if (layerType === 'polygon') {
            //layer.getLatLngs()得到的多边形的经纬度集合，多边形得到的是一个二维数组，这里要取里面的数组，一定要注意
            let latlng = layer.getLatLngs()[0];
            //一个自定义的计算面积的函数
            let area = '<div>' + this.formatArea(latlng) + '</div>';
            layer.bindPopup(area).openPopup();
          } else if (layerType === 'polyline') {
            //polyline得到的是一个一维数组，直接使用
            let latlng = layer.getLatLngs();
            //一个自定义的计算长度的函数
            let distance = '<div>' + this.formatLength(latlng) + '</div>';
            layer.bindPopup(distance).openPopup();
          }
        });
      },
      // 绘制线段
      drawPolyline() {
        //添加画图的提示信息
        L.drawLocal.draw.handlers.polyline = {
          tooltip: {
            start: '点击地图开始画线',
            cont: '继续选择',
            end: '双击完成绘制'
          }
        };
        this.polylineHander = new L.Draw.Polyline(this.map, {
          shapeOptions: {
            weight: 8,
            color: '#ff0000',
            opacity: 0.8
          }
        });
      },
      // 获取面积 polygon [{lat:30,lng:104},{lat:30,lng:104},{lat:30,lng:104}]
      formatArea(polygon) {
        //L.GeometryUtil.geodesicArea(),返回number类型的数据，单位是平方米，这里做了一下转化
        let seeArea = L.GeometryUtil.geodesicArea(polygon);
        let area = (seeArea / 666.667).toFixed(2) + '亩'; // 亩
        return area;
      },
      // 获取长度 line[{lat:30,lng:104},{lat:30,lng:104},{lat:30,lng:104}]
      formatLength(line) {
        let dis = 0;
        for (let i = 0; i < line.length - 1; i++) {
          let start = line[i];
          let end = line[i + 1];
          dis += L.latLng([start.lat, start.lng]).distanceTo([end.lat, end.lng]); //计算两个点之间的距离，并累加
        }
        //结果得到的也是number类型，单位是 米
        return (dis / 10e2).toFixed(2) + 'km';
      },
      toBounds(bounds) {
        if (bounds) {
          this.map.fitBounds(bounds);
        } else {
          this.map.flyTo([35.639, 105.55], 4);
        }
      },
      addSpot() {
        let wkt = f_shape.split(';').pop();
        let geojson = wellknown.parse(wkt);
        let spotlayer = L.geoJSON(geojson, {
          style: { color: '#f00', weight: 1 }
        });
        this.spotGroup.addLayer(spotlayer);
        this.map.fitBounds(spotlayer.getBounds());
      },
      // 清除所有
      clearAll() {
        this.drawGroup.clearLayers();
        this.spotGroup.clearLayers();
      }
    }
  };
</script>

<style lang="scss" scoped>
  .common-map {
    width: 100%;
    height: 100%;
    .map-container {
      width: 100%;
      height: 100%;
    }
    .map-tool2 {
      position: absolute;
      top: 100px;
      right: 20px;
      z-index: $--zindex-map-float-box;
    }
    .map-btn {
      width: 60px;
      height: 60px;
      line-height: 60px;
      text-align: center;
      border-radius: 6px;
      padding: 4px;
      box-sizing: border-box;
      background-color: #09f;
      cursor: pointer;
      color: #fff;
    }
  }
</style>
